package api

import (
	"cgs-server/helper"
	"cgs-server/server"
	"cgs-server/server/base"
	"cgs-server/server/cgs/app/models"
	"cgs-server/server/cgs/app/service"
	"cgs-server/server/cgs/app/store"
	"go.mongodb.org/mongo-driver/bson"
	"net/http"
)

type WorksheetViewHandler struct {
	// srv service
	srv service.Service
	// store
	store store.Factory
}

func NewWorksheetViewHandler(store store.Factory) *WorksheetViewHandler {
	return &WorksheetViewHandler{
		srv:   service.NewService(store),
		store: store,
	}
}

func (wg *WorksheetViewHandler) Get(w http.ResponseWriter, r *http.Request) {

}

func (wg *WorksheetViewHandler) Save(w http.ResponseWriter, r *http.Request) {
	var wsView models.WorksheetView
	err := helper.ReadRequestBody(&wsView, w, r)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	user, err := base.GetCurrentUser(r)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	err = wg.srv.WorksheetView().Save(&wsView, user)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	_, _ = helper.WriteJSON(w, server.OK().WithData(bson.M{"id": wsView.Id.Hex()}))
}

func (wg *WorksheetViewHandler) Delete(w http.ResponseWriter, r *http.Request) {
	viewId := r.FormValue("id")
	if viewId == "" {
		_, _ = helper.WriteJSON(w, server.Fail("worksheet view id is required"))
		return
	}
	user, err := base.GetCurrentUser(r)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	err = wg.srv.WorksheetView().Delete(viewId, user)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	_, _ = helper.WriteJSON(w, server.OK())
}

func (wg *WorksheetViewHandler) Update(w http.ResponseWriter, r *http.Request) {
	var wsView models.WorksheetView
	err := helper.ReadRequestBody(&wsView, w, r)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	user, err := base.GetCurrentUser(r)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	err = wg.srv.WorksheetView().Update(&wsView, user)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	_, _ = helper.WriteJSON(w, server.OK())
}
